<template>
  <div class="app-container app-container-next">
    <el-card class="box-card" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'freight-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <el-row>
        <el-col :span="18">
          <el-form ref="freightForm" :inline="false" :model="freight" :rules="rules" class="custom-form">
            <el-form-item label="区域方案名称" prop="name" class="hasWidth">
              <template #label>
                <div class="custom-header">
                  <div class="label">
                    区域方案名称 <span class="required">*</span><span class="desc">（该名称不会展示给客户查看）</span>
                  </div>
                </div>
              </template>
              <el-input maxlength="50" show-word-limit v-model="freight.name" placeholder="请输入区域方案名称"
                        style="width: 100%"/>
            </el-form-item>
            <el-form-item label="配送区域" prop="countryCodeList" class="hasWidth" style="border-bottom: 1px solid #EBEEF5">
              <template #label>
                <div class="custom-header">
                  <div class="label">
                    配送区域 <span class="required">*</span><span class="desc">（添加当前方案适用的国家/地区）</span>
                  </div>
                  <div class="expand">
                    <span @click="showList = !showList">已添加{{tableCountryList.length}}个国家/地区 <i :class="showList ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
                    <el-button type="primary" size="small" @click="openCountryForm">添加国家/地区</el-button>
                  </div>
                </div>
              </template>
              <el-table :data="tableCountryList" v-show="showList">
                <el-table-column label="国家/地区" prop="countryName"></el-table-column>
                <el-table-column label="操作" prop="">
                  <template slot-scope="scope">
                    <el-button size="mini" plain type="danger" @click="removeCountry(scope.$index, scope.row.code)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="运费方案" prop="freightDetailList" class="hasWidth">
              <template #label>
                <div class="custom-header">
                  <div class="label">
                    运费方案 <span class="required">*</span>
                  </div>
                  <el-button type="primary" size="small" @click="showFreightDetailForm">添加运费方案</el-button>
                </div>
              </template>
              <el-table :data="freight.freightDetailList">
                <el-table-column label="方案名称" prop="name"></el-table-column>
                <el-table-column label="运费" prop="freight">
                  <template slot-scope="{row}">
                    {{ row.freight }} {{currencyType}}
                  </template>
                </el-table-column>
                <el-table-column label="计算规则" prop="ruleText">
                  <template slot-scope="{row}">
                    {{ generateRuleText(row.ruleType, row.minValue, row.maxValue) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" prop="">
                  <template slot-scope="scope">
                    <el-button size="mini" plain type="primary" @click="editFreightDetail(scope.$index)">修改</el-button>
                    <el-button size="mini" plain type="danger" @click="removeFreightDetail(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit('freightForm')" :loading="submitLoading">保存</el-button>
              <el-button @click="handleReset('freightForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <el-drawer
        size="400px"
        title="区域设置"
        :wrapperClosable="false"
        :visible.sync="countryFormVisible"
        @close="closeCountryForm"
        class="region-setting-panel">
      <div class="region-panel">
        <div class="region-panel-title">
          <el-input
              @keyup.enter.native="searchFreightTree"
              placeholder="输入国家名进行过滤"
              v-model="filterText">
          </el-input>
          <el-button type="primary" size="small" class="search-btn" @click="searchFreightTree">搜索</el-button>
        </div>
        <el-tree
            ref="distTree"
            show-checkbox
            :data="distTree"
            :props="defaultProps"
            class="filter-tree"
            node-key="code"
            :default-checked-keys="districtList"
        >
          <span class="custom-tree-node" slot-scope="{ data}">
               {{ data.title }}
        </span>
        </el-tree>
        <div class="footer">
          <el-button type="primary" size="small" @click="saveCountryForm">确定</el-button>
        </div>
      </div>
    </el-drawer>
    <el-drawer
        size="600px"
        :title="freightFormTitle"
        :wrapperClosable="false"
        :visible.sync="freightFormVisible"
        class="region-setting-panel">
      <div class="freightDetail">
        <el-form :model="freightDetail" :rules="freightDetailRules" ref="freightDetailForm" label-width="100px"
                 class="demo-ruleForm"
                 label-position="top">
          <el-form-item label="" prop="name" placeholder="请输入">
            <template #label>
              <div class="sit-customer-label">
                方案名称
                <span>（顾客选择物流方案时展示）</span>
              </div>
            </template>
            <el-input v-model="freightDetail.name" maxlength="30" show-word-limit placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="" prop="description">
            <template #label>
              <div class="sit-customer-label">
                方案说明
                <span>（顾客选择物流方案时展示）</span>
              </div>
            </template>
            <el-input v-model="freightDetail.description" type="textarea" maxlength="100" show-word-limit
                      placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="规则设置" prop="rule">
            <div class="inline">
              <el-select v-model="freightDetail.ruleType" placeholder="请选择" class="inline-item">
                <el-option label="订单价格" :value=1></el-option>
                <el-option label="商品数量" :value=2></el-option>
                <el-option label="商品重量" :value=3></el-option>
              </el-select>
              <el-form-item prop="minValue" class="inline-item">
                <el-input v-model="freightDetail.minValue" @input.native="oninput($event, 'minValue')"
                          placeholder="0"></el-input>
              </el-form-item>
              ~
              <el-form-item prop="maxValue" class="inline-item">
                <el-input v-model="freightDetail.maxValue" @input.native="oninput($event, 'maxValue')"
                          placeholder="无限"></el-input>
              </el-form-item>
              <el-button type="info" class="inline-item" v-if="freightDetail.ruleType===1"
                         style="background: #F5F7FA;color: #909399;border: 1px solid #DCDFE6;">{{currencyType}}
              </el-button>
              <el-button type="info" class="inline-item" v-if="freightDetail.ruleType===2"
                         style="background: #F5F7FA;color: #909399;border: 1px solid #DCDFE6;">件
              </el-button>
              <el-button type="info" class="inline-item" v-if="freightDetail.ruleType===3"
                         style="background: #F5F7FA;color: #909399;border: 1px solid #DCDFE6;">g
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="运费" prop="freight">
            <el-input v-model="freightDetail.freight" placeholder="请输入" @input.native="oninput($event, 'freight')">
              <template slot="append">{{currencyType}}</template>
            </el-input>
          </el-form-item>
          <div class="footer">
            <el-button type="primary" @click="closeFreightDetailForm('freightDetailForm')">保存</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {addFreight, getFreightTree} from '@/api/site';
import {debounce} from '@/utils/utils';
import {mapGetters} from 'vuex';

export default {
    name: 'freight-add',
    data () {
        const validateMin = (rule, value, callback) => {
            let reg2 = /^(([1-9]{1}\d*)|(0{1}))(\.\d+)?$/;
            let reg1 = /^(([1-9]{1}\d*)|(0{1}))?$/;
            let one = Number(value);
            let max = Number(this.freightDetail.maxValue);
            let text = this.freightDetail.ruleType === 2 ? '只能输入大于零的整数' : '只能输入大于零的正数';
            if (((!max && !isNaN(max)) || (!one && !isNaN(one))) && reg1.test(one)) {
                return callback();
            }
            if (this.freightDetail.ruleType === 2 && !reg1.test(one)) {
                return callback(new Error(text));
            } else if (!reg2.test(one)) {
                return callback(new Error(text));
            } else if (!!max && one > max) {
                return callback(new Error('输入值不得大于最大阈值'));
            }
            return callback();
        };
        const validateMax = (rule, value, callback) => {
            let reg2 = /^(([1-9]{1}\d*)|(0{1}))(\.\d+)?$/;
            let reg1 = /^(([1-9]{1}\d*)|(0{1}))?$/;
            let one = Number(value);
            const min = Number(this.freightDetail.minValue);
            let text = this.freightDetail.ruleType === 2 ? '只能输入大于零的整数' : '只能输入大于零的正数';
            if ((!min && !isNaN(min)) || (!one && !isNaN(one))) {
                return callback();
            }
            if (this.freightDetail.ruleType === 2 && !reg1.test(one)) {
                return callback(new Error(text));
            } else if (!reg2.test(one)) {
                return callback(new Error(text));
            } else if (!!min && one < min) {
                return callback(new Error('输入值不得小于最小阈值'));
            }
            return callback();
        };
        return {
            showList: true,
            freight: {
                name: '',
                countryCodes: '',
                countryNames: '',
                countryCodeList: [],
                countryNameList: [],
                freightDetailList: []
            },
            rules: {
                name: [
                    {required: true, message: '请输入区域方案名称', trigger: 'blur'}
                ]
            },
            tableCountryList: [],
            submitLoading: false,

            freightFormTitle: '新增运费方案',
            freightFormVisible: false,
            countryFormVisible: false,
            searchMethod: false,
            distTree: [],
            defaultProps: {children: 'children', label: 'label'},
            districtList: [],
            filterText: '',
            freightDetail: {
                name: '',
                ruleType: 1,
                minValue: null,
                maxValue: null,
                type: 'add'
            },
            freightDetailRules: {
                name: [
                    {required: true, message: '请输入方案名称', trigger: 'blur'}
                ],
                freight: [
                    {required: true, message: '请输入运费', trigger: 'blur'},
                    {type: 'string', pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: '运费不合法', trigger: 'blur'}
                ],
                minValue: [
                    {validator: validateMin, trigger: 'blur'}
                ],
                maxValue: [
                    {validator: validateMax, trigger: 'blur'}
                ]
            }
        };
    },
    computed: {
        ...mapGetters(['siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencyType () {
            return this.siteInfo.currencyType;
        }
    },
    methods: {
        getFreightTree () {
            return new Promise(resolve => {
                getFreightTree({siteId: this.siteId, regionName: this.filterText, freightId: this.freightId}).then(res => {
                    const {data} = res;
                    data.forEach(item => {
                        if (item.children && item.children.every(a => a.disabled)) {
                            item.disabled = true;
                        }
                    });
                    this.distTree = data;
                    resolve();
                });
            });
        },
        // 搜索
        searchFreightTree () {
            this.searchMethod = true;
            this.getFreightTree();
        },
        handleSubmit (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    if (this.freight.countryCodeList.length === 0) {
                        this.$message.error('请添加配送区域!');
                        return;
                    }
                    if (this.freight.freightDetailList.length === 0) {
                        this.$message.error('请添加运费方案!');
                        return;
                    }
                    this.submitLoading = true;
                    this.freight.siteId = this.siteId;
                    this.freight.countryCodes = this.freight.countryCodeList.join(',');
                    this.freight.countryNames = this.freight.countryNameList.join(',');

                    let freightForSave = JSON.parse(JSON.stringify(this.freight));

                    freightForSave.freightDetailList.forEach(detail => {
                        let freight = detail.freight;
                        detail.freight = freight * 100;
                        if (detail.ruleType === 1) {
                            let minValue = detail.minValue;
                            let maxValue = detail.maxValue;
                            detail.minValue = minValue * 100;
                            detail.maxValue = maxValue * 100;
                        }
                    });
                    addFreight(freightForSave).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('新增成功');
                            this.$router.push({name: 'freight-list'});
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        handleReset () {
            this.$router.push({name: 'freight-list'});
        },
        removeCountry (index, code) {
            this.tableCountryList.splice(index, 1);
            this.freight.countryCodeList = this.tableCountryList.map(res => res.code);
            this.freight.countryNameList = this.tableCountryList.map(res => res.countryName);
            let i = this.districtList.findIndex(res => res === code);
            this.districtList.splice(i, 1);
        },
        openCountryForm () {
            this.countryFormVisible = true;
            this.getFreightTree().then(() => {
                this.$refs.distTree.setCheckedKeys(this.districtList);
            });
        },
        closeCountryForm () {
            this.$refs.distTree.setCheckedKeys(this.districtList);
        },
        saveCountryForm () {
            this.countryFormVisible = false;
            if (!this.searchMethod) {
                this.tableCountryList = [];
                this.freight.countryCodeList = [];
                this.freight.countryNameList = [];
                this.districtList = [];
            }
            this.$refs.distTree.getCheckedNodes().forEach(node => {
                if (node.title === '亚洲' || node.title === '欧洲' || node.title === '非洲' || node.title === '北美洲' || node.title === '南美洲' || node.title === '大洋洲' || node.title === '南极洲') {
                    return;
                }
                this.tableCountryList.push({
                    code: node.code,
                    countryName: node.title
                });
                this.districtList.push(node.code);
                this.freight.countryCodeList.push(node.code);
                this.freight.countryNameList.push(node.title);
                this.searchMethod = false;
                this.filterText = '';
            });
        },
        removeFreightDetail (index) {
            this.freight.freightDetailList.splice(index, 1);
        },
        checkValue (value) {
            if (value === undefined || value === null || value === '' || isNaN(value)) {
                return false;
            }
            return true;
        },
        generateRuleText (ruleType, minValue, maxValue) {
            let ruleText = '';
            let prefixText = '';
            let endText = '';
            if (ruleType === 1) {
                prefixText = '价格';
                endText = this.currencyType;
            } else if (ruleType === 2) {
                prefixText = '数量';
                endText = '件';
            } else if (ruleType === 3) {
                prefixText = '重量';
                endText = 'g';
            }
            if (!this.checkValue(minValue) && !this.checkValue(maxValue)) {
                ruleText = '所有订单';
            }
            if (!this.checkValue(minValue) && this.checkValue(maxValue)) {
                ruleText = prefixText + ' 0' + '-' + maxValue + ' ' + endText;
            }
            if (this.checkValue(minValue) && !this.checkValue(maxValue)) {
                ruleText = prefixText + '>=' + minValue + ' ' + endText;
            }
            if (this.checkValue(minValue) && this.checkValue(maxValue)) {
                ruleText = prefixText + minValue + '-' + maxValue + ' ' + endText;
            }
            return ruleText;
        },
        showFreightDetailForm () {
            this.freightDetail = {
                name: '',
                ruleType: 1,
                minValue: null,
                maxValue: null,
                freight: null,
                type: 'add'
            };
            this.freightFormTitle = '新增运费方案';
            this.freightFormVisible = true;
        },
        editFreightDetail (index) {
            this.freightFormTitle = '修改运费方案';
            let freightDetail = JSON.parse(JSON.stringify(this.freight.freightDetailList))[index];
            freightDetail.type = 'edit';
            freightDetail.index = index;
            this.freightDetail = freightDetail;
            this.freightFormVisible = true;
        },
        closeFreightDetailForm (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    // if (this.freight.freightDetailList.some(res => res.name === this.freightDetail.name) && this.freightDetail.type === 'add') {
                    //     return this.$message({type: 'error', message: '名称不能重复!'});
                    // }
                    this.freightFormVisible = false;
                    if (this.freightDetail.type === 'edit') {
                        this.freight.freightDetailList[this.freightDetail['index']] = Object.assign(this.freight.freightDetailList[this.freightDetail['index']], this.freightDetail);
                    } else {
                        this.freight.freightDetailList.push(this.freightDetail);
                    }
                    this.freightDetail = {
                        name: '',
                        ruleType: 1,
                        minValue: null,
                        maxValue: null,
                        freight: null,
                        type: 'add'
                    };
                    this.freightFormTitle = '新增运费方案';
                }
            });
        },
        oninput: debounce(function (e, type) {
            let reg2 = /^(([1-9]{1}\d*)|(0{1}))(\.\d+)?$/;
            if ((this.freightDetail.ruleType === 1 || type === 'freight') && reg2.test(this.freightDetail[type])) {
                this.freightDetail[type] = this.freightDetail[type].match(/^\d*(\.?\d{0,2})/g)[0];
            }
        }, 600)
    }
};

</script>

<style scoped lang="scss">
.custom-header {
  padding: 0;
  height: 68px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .label {
    font-size: 18px;
    line-height: 25px;
  }

  .required {
    color: #db6060;
  }

  .desc {
    color: #7e849c;
    font-size: 14px;
    margin-left: 10px;
  }
}

.region-panel {
  padding: 0 20px;
  overflow: auto;
  margin-bottom: 100px;

  &-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .search-btn {
      margin-left: 20px;
    }
  }

  .footer {
    z-index: 222;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 70px;
    background: #eef0f5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 20px;

    .country_selected {
      margin-right: 10px;
      color: #212121;
      font-size: 12px;
    }
  }
}

.freightDetail {
  padding: 0 20px;

  .sit-customer-label {
    display: flex;
    align-items: center;

    span {
      font-size: 12px;
      color: #7e849d;
      margin-left: 10px;
    }
  }

  .inline {
    display: flex;
    align-content: center;

    .inline-item:not(:last-child) {
      margin-right: 10px;
    }
  }

  .footer {
    z-index: 222;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 70px;
    background: #eef0f5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 20px;

    .country_selected {
      margin-right: 10px;
      color: #212121;
      font-size: 12px;
    }
  }
}

</style>

<style lang="scss">
.filter-tree {
  .el-tree-node {
    .el-tree-node__content {
      display: flex;
      align-items: center;
      height: 40px;

      .custom-tree-node {
        display: flex;
        align-items: center;

        img {
          margin-right: 10px;
        }
      }
    }
  }
}

.region-setting-panel {
  .el-drawer__body {
    height: 100%;
    overflow: auto;
  }
}

.freightDetail {
  .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    display: none;
  }
}
</style>
